from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse
from user.models import User,Address
import random,string,redis
from captcha.image import ImageCaptcha
from django.contrib.auth.hashers import check_password,make_password
from django.http.response import JsonResponse
from django.db.models import Q
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
from user.serializer import UserSer,AddressSer

# Create your views here.
# 校验用户名
class CheckUser(APIView):
    def get(self,request,name):
        salt = User.objects.filter(username=name).count()
        if salt > 0:
            return Response({'msg':'用户已存在','code':400})
        else:
            return Response({'code':200})

# 校验手机号
class CheckMobile(APIView):
    def get(self,request,mobile):
        salt = User.objects.filter(mobile=mobile).count()
        if salt > 0:
            return Response({'msg':'手机号已存在','code':400})
        else:
            return Response({'code':200})

# 生成图片验证码
class GetImage(APIView):
    def get(self,request,img_id):
        salt = ''.join(random.sample(string.ascii_letters + string.digits,4))
        img = ImageCaptcha()
        image = img.generate(salt)
        redis_cli = redis.Redis(password='123456')
        imgID = 'img_{}'.format(img_id)
        redis_cli.setex(imgID,60,salt)
        return HttpResponse(image,content_type='image/jpg')

# 校验图片验证码
class CheckImage(APIView):
    def get(self,request):
        image_id = request.query_params.get('imageCodeID')
        image_code = request.query_params.get('imageCode')
        redis_cli = redis.Redis(password='123456')
        result = redis_cli.get('img_{}'.format(image_id))
        if result:
            try:
                result.decode().lower() != image_code.lower()
            except Exception as e:
                return Response({'code':400,'msg':'验证码输入错误'})
            else:
                return Response({'code':200})
        else:
            return Response({'msg':'验证码已过期','code':400})

# 注册
class Register(APIView):
    def post(self,request):
        username = request.data.get('userName')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        agree = request.data.get('agree')

        if not all([username,pwd,mobile]):
            return Register({'msg':'请完善注册信息'})

        if not agree:
            return Register({'msg':'请勾选同意协议'})

        User.objects.create_user(username=username,password=pwd,mobile=mobile)
        return Response({'msg':'注册成功','code':200})

# 登录
class Login(APIView):
    def post(self,request):
        user_name = request.data.get('user')
        pwd = request.data.get('pwd')
        try:
            user = User.objects.get(Q(username=user_name) | Q(mobile=user_name))
        except Exception as e:
            return Response({'msg':'用户名不存在','code':400})
        is_correct = check_password(pwd,user.password)
        if is_correct:
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            resp = Response({'msg':'登录成功','code':200,'user':{'userName':user.username},'token':token})
            resp.set_cookie('token',token)
            return resp
        else:
            return Response({'msg':'账号密码错误'})

# 退出登录
class LoginOut(APIView):
    def post(self,request):
        token =request.COOKIES.get('token')
        if token:
            del token
        return Response({'msg':'退出成功','code':200})

# 用户信息展示
class UserInfo(APIView):
    def post(self,request):
        name = request.data.get('user').get('userName')
        try:
            user = User.objects.get(username=name)
        except Exception as e:
            return Response({'msg':'请先登录','code':400})
        addresses = user.address_set.all()
        user_addr = []
        for addr in addresses:
            user_addr.append(AddressSer(addr).data)
        data = {
            'username':user.username,
            'mobile':user.mobile,
            'addresses':user_addr,
        }
        return Response({'msg':'获取用户信息成功','code':200,'userInfo':data})

# 添加收货地址
class AddAddresses(APIView):
    def post(self,request):
        name = request.data.get('user').get('userName')
        try:
            user = User.objects.get(username=name)
        except Exception as e:
            return Response({'msg':'请先登录','code':400})
        receiver = request.data.get('receiver')
        receive_mobile = request.data.get('receive_mobile')
        receive_addr = request.data.get('receive_addr')
        is_default = request.data.get('is_default')
        if not all([receiver,receive_mobile,receive_addr,is_default]):
            return Response({'msg':'此时数据不全，请完善地址信息','code':400})
        add = Address.objects.create(user_id=user.id,is_default=is_default,receiver=receiver,receive_mobile=receive_mobile,receive_addr=receive_addr)
        ser = AddressSer(add)
        return Response({'msg':'添加成功','code':200,'addr':ser.data})

# 修改用户信息
class UpdateUserInfo(APIView):
    def post(self,request):
        name = request.data.get('user').get('userName')
        try:
            user = User.objects.get(username=name)
        except Exception as e:
            return Response({'msg':'请先登录','code':400})
        phone = request.data.get('phone')
        addr_list = request.data.get('addrs')
        # 更新：注意对于地址信息都要进行修改，要遍历写入数据库
        user.mobile = phone
        user.save()
        for new_addr in addr_list:
            print(">>>>", new_addr)
            # 判断是否有更新, 若没有返回对象,要更新, 若返回的有对象,不用更新
            addr = Address.objects.filter(id=new_addr.get('id'),
                                          receiver=new_addr.get("receiver"),
                                          receive_mobile=new_addr.get("receive_mobile"),
                                          receive_addr=new_addr.get("receive_addr"),
                                          )
            print(addr)
            if not addr:
                # 此时说明要更新
                addrs = Address.objects.get(id=new_addr.get('id'))
                addrs.receiver = new_addr.get("receiver")
                addrs.receive_mobile = new_addr.get("receive_mobile")
                addrs.receive_addr = new_addr.get("receive_addr")
                addrs.save()

        return Response({'msg': "更新信息成功", "code": 200})

# 修改密码
class UpdatePassword(APIView):
    def post(self, request):
        name = request.data.get('user')
        old_pwd = request.data.get('originPw')
        new_pwd = request.data.get('newPw')
        confirm_pwd = request.data.get('confirmNewPw')
        if new_pwd != confirm_pwd:
            return Response({"msg": '输入的两次密码不一致,请重新输入', "code": 400})
        if old_pwd == new_pwd:
            return Response({"msg": '新密码和旧密码一样,请重新输入', "code":400})
        try:
            user = User.objects.get(username=name)
        except Exception  as e:
            return Response({"msg": "获取用户失败", "code": 400})
        user.password = make_password(new_pwd)
        user.save()
        return Response({'msg': "修改密码成功", "code": 200})

#  删除地址
class DelAddressInfo(APIView):
    def post(self,request):
        add_id = request.data.get('addr_id')
        try:
            address = Address.objects.get(id=add_id)
        except Exception as e:
            return Response({'msg':'获取地址信息失败',"code":400})
        address.delete()
        return Response({"msg":"删除成功!","code":200})

